//
//  RefreshControl.swift
//  微博
//
//  Created by mac on 15/12/22.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SnapKit
//刷新状态
enum RefreshStatue: Int {
    case Normal = 0 //默认状态
    case Pulling = 1 // 用户下拉还没有松手的状态
    case refreshing = 2 // 正在刷新的状态
}

//定义刷新控件的宽度
let KrefreshHeight:CGFloat = 60
class RefreshControl: UIControl {
    //属性
    //记录属性
    var oldStatue :RefreshStatue = .Normal
    
    var statue :RefreshStatue = .Normal {
        didSet{
            switch statue {
            case .Pulling:
                print("准备起飞")
                tipLabel.text = "准备起飞"
                //设置箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .refreshing:
                print("正在起飞")
                tipLabel.text = "正在起飞"
                arrowIcon.hidden = true
                loadIcon.startAnimating()
                //主动触发响应事件
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollView!.contentInset
                    inset.top += KrefreshHeight
                    self.scrollView?.contentInset = inset
                })
                //当起飞的时候,发送valueChange的方法去发送响应
                sendActionsForControlEvents(.ValueChanged)
            case .Normal:
                print("下拉起飞")
                tipLabel.text = "下拉起飞"
                arrowIcon.hidden = false
                loadIcon.stopAnimating()
                if oldStatue == .refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView!.contentInset
                        inset.top -= KrefreshHeight
                        self.scrollView?.contentInset = inset
                    })
                }
                //设置箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
            }
            //保存上一次的状态
            oldStatue = statue
        }
    }
    
    
  //重写构造方法
    override init(frame: CGRect) {
        //在内部定义控件视图
        let rect = CGRect(x: 0, y: -KrefreshHeight, width: screenWidth, height: KrefreshHeight)
        super.init(frame: rect)
        self.backgroundColor = UIColor.whiteColor()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //在view的生命周期里添加父控件的kvo方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        //如果父控件是scrollview的话,记录,并添加kvo观察者模式
        if let scroll = newSuperview as? UIScrollView {
            self.scrollView = scroll
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        }
    }
    
    //延迟结束动画
    func endRefreshing() {
    
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1) * Int64(NSEC_PER_SEC))
        //默认延迟一秒
        dispatch_after(when, dispatch_get_main_queue()) { () -> Void in
            //设置默认状态
            self.statue = .Normal
        }
    }
    
    //观察者模式
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(change)
        //获取tableView的临界值
        let insetTop = scrollView?.contentInset.top ?? 0
        let condationValue = -(KrefreshHeight + insetTop)
        let offsetY = scrollView?.contentOffset.y ?? 0
        //判断
        if scrollView!.dragging {
            if statue == .Normal && offsetY < condationValue {
                //进入下拉起飞的状态
                statue = .Pulling
            }else if statue == .Pulling && offsetY > condationValue {
                statue = .Normal
            }
        } else {
            if statue == .Pulling {
                statue = .refreshing
            }
        }
    }
    
    //移除观察者
    deinit {
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    //设置ui
    private func setupUI() {
        //添加控件
        addSubview(arrowIcon)
        addSubview(tipLabel)
        addSubview(loadIcon)
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        loadIcon.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
    }
    
    //记录父控件
    var scrollView:UIScrollView?
    //懒加载控件
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLabel: UILabel = UILabel(content: "下拉刷新", color: UIColor.grayColor(), fontSize: 14)
    private lazy var loadIcon: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)

}
